import os
import psycopg2
import json
from flask import Flask, request, jsonify

# 创建Flask应用实例
app = Flask(__name__)

# 数据库连接配置
# 从环境变量获取数据库连接参数，如果未设置则使用远程数据库默认值
db_conn = psycopg2.connect(
    host=os.getenv("DB_HOST", "ecs.sec.hn.cn"),
    port=os.getenv("DB_PORT", "5432"),
    user=os.getenv("DB_USER", "user_kwmBAP"),
    password=os.getenv("DB_PASSWORD", "TeHeZKPzzr6mZ6R4"),
    dbname=os.getenv("DB_NAME", "auditdb")
)
# 设置自动提交事务
db_conn.autocommit = True
# 创建数据库游标对象
cursor = db_conn.cursor()

@app.route("/detect", methods=["POST"])
def detect():
    """
    检测文本中的敏感信息接口
    接收文本数据，调用C库检测手机号、身份证号、邮箱和银行卡号，并将结果存储到数据库
    """
    # 获取请求中的JSON数据
    data = request.json
    # 提取文本内容，默认为空字符串
    text = data.get("text", "")
    
    # 调用 C 库处理
    import ctypes, os
    # 获取C库路径
    lib_path = os.path.abspath("../c_core/libcore.so")
    # 加载C动态库
    core = ctypes.CDLL(lib_path)
    # 设置C函数参数类型
    core.process_data.argtypes = [ctypes.c_char_p, ctypes.c_char_p]
    core.contains_phone_number.argtypes = [ctypes.c_char_p]
    core.contains_id_card.argtypes = [ctypes.c_char_p]
    core.contains_email.argtypes = [ctypes.c_char_p]
    core.contains_credit_card.argtypes = [ctypes.c_char_p]
    # 设置C函数返回值类型
    core.contains_phone_number.restype = ctypes.c_int
    core.contains_id_card.restype = ctypes.c_int
    core.contains_email.restype = ctypes.c_int
    core.contains_credit_card.restype = ctypes.c_int
    
    # 调用C函数检测敏感信息
    has_phone = core.contains_phone_number(text.encode('utf-8'))
    has_id_card = core.contains_id_card(text.encode('utf-8'))
    has_email = core.contains_email(text.encode('utf-8'))
    has_credit_card = core.contains_credit_card(text.encode('utf-8'))
    
    # 生成输出结果
    output = ctypes.create_string_buffer(len(text)*2)  # 增加缓冲区大小以适应可能的输出增长
    core.process_data(text.encode('utf-8'), output)
    
    # 构建检测结果列表
    issues = []
    if has_phone == 1:
        issues.append("包含手机号码")
    if has_id_card == 1:
        issues.append("包含身份证号码")
    if has_email == 1:
        issues.append("包含邮箱地址")
    if has_credit_card == 1:
        issues.append("包含银行卡号")
    
    # 构造返回结果
    result = {
        "input": text,
        "output": output.value.decode('utf-8'),
        "issues": issues,
        "is_sensitive": len(issues) > 0
    }

    # 将原始数据写入审计日志表
    cursor.execute("INSERT INTO audit_log(data) VALUES(%s)", (text,))
    # 返回JSON格式的检测结果
    return jsonify(result)

@app.route("/compliance", methods=["POST"])
def compliance():
    """
    合规检查接口
    检查文本是否符合数据安全规范（不包含敏感信息）
    """
    # 获取请求中的JSON数据
    data = request.json
    # 提取文本内容，默认为空字符串
    text = data.get("text", "")
    
    # 调用 C 库处理
    import ctypes, os
    # 获取C库路径
    lib_path = os.path.abspath("../c_core/libcore.so")
    # 加载C动态库
    core = ctypes.CDLL(lib_path)
    # 设置C函数参数类型和返回值类型
    core.contains_phone_number.argtypes = [ctypes.c_char_p]
    core.contains_phone_number.restype = ctypes.c_int
    core.contains_id_card.argtypes = [ctypes.c_char_p]
    core.contains_id_card.restype = ctypes.c_int
    core.contains_email.argtypes = [ctypes.c_char_p]
    core.contains_email.restype = ctypes.c_int
    core.contains_credit_card.argtypes = [ctypes.c_char_p]
    core.contains_credit_card.restype = ctypes.c_int
    
    # 调用C函数检测敏感信息
    has_phone = core.contains_phone_number(text.encode('utf-8'))
    has_id_card = core.contains_id_card(text.encode('utf-8'))
    has_email = core.contains_email(text.encode('utf-8'))
    has_credit_card = core.contains_credit_card(text.encode('utf-8'))
    
    # 构建合规检查问题列表
    issues = []
    if has_phone == 1:
        issues.append("包含手机号码")
    if has_id_card == 1:
        issues.append("包含身份证号码")
    if has_email == 1:
        issues.append("包含邮箱地址")
    if has_credit_card == 1:
        issues.append("包含银行卡号")
    
    # 判断是否合规（简单示例：不包含敏感信息即合规）
    is_compliant = len(issues) == 0
    
    # 构造返回结果
    result = {
        "data": text,
        "is_compliant": is_compliant,
        "issues": issues
    }
    
    # 将合规检查结果存储到数据库
    issues_json = json.dumps(issues)
    cursor.execute(
        "INSERT INTO compliance_results(data, is_compliant, issues) VALUES(%s, %s, %s)",
        (text, is_compliant, issues_json)
    )
    
    # 返回JSON格式的合规检查结果
    return jsonify(result)

# 程序入口点
if __name__ == "__main__":
    # 启动Flask应用，监听所有网络接口的5000端口
    app.run(host="0.0.0.0", port=5000)